package org.dtrd.config.sign.filter;

import lombok.extern.slf4j.Slf4j;
import org.dtrd.config.sign.util.BodyReaderHttpServletRequestWrapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author 萧
 * @date:2021-09-06 9:11 下午
 **/
@WebFilter(filterName = "bodyReaderFilter", urlPatterns = "/*")
@Slf4j
public class BodyReaderFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // do nothing
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if (request instanceof HttpServletRequest) {
            requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
        }
        if (requestWrapper == null) {
//            log.info("BodyReaderFilter.doFilter.[request, response, chain] requestWrapper is null ");
            chain.doFilter(request, response);
        } else {
//            log.info("BodyReaderFilter.doFilter.[request, response, chain] requestWrapper is not null ");
            chain.doFilter(requestWrapper, response);
        }

    }

    @Override
    public void destroy() {
        // do nothing

    }
}